<template>
  <!-- 流量采集  -->
  <search-table
      :columns="taskCol" 
      :data="targetAllotList"
      :total="targetAllotTotal"
      :page.sync="queryTargetAllotInfo.pageIndex"
      :size.sync="queryTargetAllotInfo.pageSize"
      @change-page="queryTaskList"
      @change-size="getTargetSize"
    >
    <template slot="search">
      <Button
        type="primary"
        ghost
        @click="showAddAndUpdate"
        style="margin-right: 15px"
      >
        <Icon type="md-add" />
        添加采集任务
      </Button>
      <!-- :disabled="accessGroupList.length == 0 || disabledAllBtn" -->
      <Input
        v-model.trim="queryTargetAllotInfo.name"
        placeholder="名称"
        clearable
        style="width: 180px; margin-right: 15px"
        @on-change="queryTaskList(1)"
      ></Input>
    </template>
    <Modal
      v-model="targetModal.show"
      :title="targetModal.title"
      :loading="targetModal.loading"
      width="700"
      class="account-target-modal"
      :mask-closable="false"
      @on-visible-change="modalVisibleChange"
      @on-ok="handleSubmit('formValidate')"
      @on-cancel="closeTargetModal('formValidate')"
    >
      <Form
         style="height: 100%;overflow: hidden"
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="80"
      >
        <div style="height: calc(100% - 48px);overflow: auto">
        <FormItem label="名称" prop="name">
          <Input
            v-model="formValidate.name"
            placeholder="请输入名称"
            clearable
            :maxlength="64"
          ></Input>
        </FormItem>
        <!-- <FormItem label="类型" prop="taskMode">
          <RadioGroup v-model="formValidate.taskMode">
            <Radio label="normal">流程任务</Radio>
            <Radio label="preset">预设临机任务</Radio>
          </RadioGroup>
        </FormItem> -->
        <FormItem label="协议" prop="metadata" style="position: relative">
          <Select filterable v-model="formValidate.metadata" placeholder="协议" clearable>
            <Option value="-1">不选择协议</Option>
            <Option value="1">ICMP</Option>
            <Option value="6">TCP</Option>
            <Option value="17">UDP</Option>
            <!-- <Option
              v-for="(item, index) in appProtocolsList"
              :value="item"
              :key="index"
            >
              {{ item }}
            </Option> -->
          </Select>
        </FormItem>
        <FormItem v-model="formValidate.selectedVmData" label="端口">
          <span class="starlet">*</span>
          <input type="hidden" />
          <div class="flex-wrap">
            <Tag
              v-for="item in formValidate.selectedVmData"
              :key="item.id"
              :name="item.name"
              closable
              @on-close="handleClose2"
              color="primary"
              type="dot"
              >{{ item.name}} - {{item.ip}}</Tag
            >
          </div>
        </FormItem>
        <div style="text-align: right">
          <Button
            type="primary"
            @click="addSelectedData"
            style="margin-right: 17px"
            >添加</Button
          >
          <Input
            placeholder="请输入设备名称"
            style="width: 210px"
            v-model="formValidate.vmName"
            clearable
          ></Input>
          <Input
            placeholder="请输入IP"
            style="width: 210px"
            v-model="formValidate.vmIP"
            clearable
          ></Input>
          <Button type="primary" @click="refreshVmList" style="margin-left: 5px"
            >搜索</Button
          >
        </div>
        <Table
          border
          :columns="columnsVmList"
          :data="dataVmList"
          style="margin-top: 10px"
          @on-selection-change="getSelectedData"
        ></Table>
        </div>
        <Page
          :total="vmTotal"
          :current="vmCurrentPage"
          :page-size="vmItemPage"
          :show-total="true"
          @on-change="switchineVmCurrentPage"
          @on-page-size-change="switchVmItemPage"
          class-name="pageStyleVm"
          show-elevator
        >
        </Page>
        <!-- <FormItem label="属性">
          <cusAttribute
            ref="cusAttribute"
            @func="getMsgFormSon"
            v-bind:msgVal="propertiesData"
          ></cusAttribute>
        </FormItem> -->
        <!-- <FormItem label="描述" prop="desc" style="margin-top: 10px">
          <Input
            v-model="formValidate.desc"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="请输入内容"
            clearable
            :maxlength="200"
          ></Input>
        </FormItem> -->
      </Form>
    </Modal>

    <Modal
      v-model="taskDeailModal"
      title="任务启动详情"
      width="80%"
      :mask-closable="false"
    >
      <Table
        ref=""
        :columns="taskDeailColumns"
        :data="taskDeailData"
        @on-expand="hostDeail"
      ></Table>
    </Modal>
  </search-table>
</template>

<script>
import { debounce } from '@/libs/utils';
import { categoryMixin } from '../hw/mixins';
import { queryTaskList, delTask, getHistoriesInfo, deployedPortsInfo, operateExecute, addTask, updateTask, deployedProjectsList, getTaskDetail } from '@/api/process/task'
import {appProtocols} from '@/api/integration3d';
import { taskCol } from '../task_new/taskMixin.js';
const validateName = (rule, value, callback) => {
  var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
  value = value.replace(/\s*/g, "");
  if (!value) {
    callback("请填写名字");
  } else {
    if (myReg.test(value)) {
      callback("名字不能包含特殊字符");
    } else {
      callback();
    }
  }
};
export default {
  name: 'trafficCollection',
  props: ['type', 'disabledAllBtn'],
  components: {  },
  mixins: [categoryMixin,taskCol],
  data () {
    const validateNum = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^([1-9]|[1-9]\\d|100)$');
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('请输入1-100的整数'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      teamName: '',
      routeParams: {
        id: this.$route.query.id,
        prjid: this.$route.query.prjid
      },
      targetModal: {
        show: false,
        title: '采集任务',
        loading: true,
        type: 1 //1添加，2修改
      },
      judgePanelType: true,//判断是修改还是保存
      workingAreaTaskId: "",//存放修改的任务id
      modifyTargetModal: {
        show: false,
        title: '修改分配',
        loading: true
      },
      accessGroupList: [],
      vmlists: [],
      allVms: [],
      queryTargetTeamInfo: {
        pageIndex: 1,
        pageSize: 200,
        available: 1,
        // sceneId:this.$route.query.id,
        industry: '',
        projectId: this.$route.query.prjid
      },
      queryTargetAllotInfo: {
        pageIndex: 1,
        pageSize: 10,
        projectId: this.$route.query.prjid,
        sceneId: this.$route.query.id
      },
      questionList: [],
      formValidate: {
        name: '',
        metadata: '-1',
        Profile: '',
        osInfo: '',
        type: '',
        configContent: '',
        selectedVmData: [],
        desc: '',
        vmName: '',
        vmIP: '',
        taskMode: 'preset',
      },
      taskTypeTable: 'mirror_flow',
      ruleValidate: {
        name: [
          { required: true, message: '', trigger: 'change', validator: validateName }
        ],
        // metadata: [
        //   { required: true, message: '请选择协议', trigger: 'change' },
        // ],
        selectedVmData: [
          { required: true, message: "请选择端口", trigger: 'change' }
        ],
        // taskMode: [
        //   { required: true, message: '', trigger: 'blur' }
        // ],
      },
      allotFormValidate: {
        createTime: '',
        externalIp: '',
        externalPort: '',
        externalServicePort: '',
        id: '',
        sceneId: '',
        subnetId: '',
        subnetName: '',
        targetId: '',
        targetName: '',
        teamId: '',
        teamName: '',
        visibility: 0,
        vmId: '',
        vmName: ''
      },
      targetTeamCol: [
        // {
        //     type: 'selection',
        //     width: 60,
        //     align: 'center',

        // },
        // {
        //     title:'任务ID',
        //     key:'id',
        //     align:'center'
        // },
        {
          title: '名称',
          key: 'name',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-left',
          width: 240
        },
        // {
        //   title: '创建者',
        //   key: 'creator',
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   width: 100,
        //   placement: 'top-left'
        // },
        {
          title: '创建时间',
          key: 'created',
          align: 'center',
          ellipsis: true,
          tooltip: true,
        },

        {
          title: '状态',
          key: 'status',
          align: 'center',
          width: 130,
          render: (h, params) => {
            let obj = this.setStatusType(params.row.status)
            return h('Tag', {
              props: {
                color: obj.color,
              },
            }, obj.str)
          }
        },
        {
          title: '协议',
          key: 'metadata',
          align: 'center',
          render: (h, params) => {
            let metadataObj = params.row.metadata || {};
            let protoNum = metadataObj.proto || ''
            let text = ''
            if (protoNum == 1) {
              text = 'ICMP'
            } else if (protoNum == 6) {
              text = 'TCP'
            } else if (protoNum == 17) {
              text = 'UDP'
            } else if (protoNum == -1) {
              text = '暂无协议'
            }
            return h('div', text)
          }
        },
        {
          title: '详情',
          key: 'overview',
          align: 'center',
          render: (h, params) => {
            let statics = params.row.overview;
            let statusGroup = [];
            if (JSON.stringify(statics) != "{}") {
              for (let i in statics) {
                let text = '';
                switch (i) {
                  case "running": text = '运行中'; break;
                  case "error": text = '失败'; break;
                  case "failed": text = '失败'; break;
                  case "completed": text = '完成'; break;
                  case "initialized": text = '初始化'; break;
                  case "starting": text = '启动中'; break;
                  case "closing": text = '关闭中'; break;
                  default: text = i; break;
                }
                statusGroup.push(h('p', {}, text + ':' + statics[i]))
              }
            }
            // console.log(statusGroup)
            return h('div', {}, statusGroup)
          }
        },
        // {
        //   title: '任务种类',
        //   key: '',
        //   align: 'center',
        //   render: (h, params) => {
        //     let _text = null;
        //     if (params.row.taskMode == "normal") {
        //       _text = "流程任务"
        //     } else if (params.row.taskMode == "temp") {
        //       _text = "实时任务"
        //     } else {
        //       _text = "预设临机任务"
        //     }
        //     return h('div', {}, _text)
        //   }
        // },
        {
          title: '操作',
          key: '-',
          align: 'center',
          width: 350,
          placement: 'top-right',
          action: true,
          render: (h, params) => {
            let _this = this;
            let taskStatus = this.getStatusColor(params.row.status).taskStatus
            let taskBtnType = this.getStatusColor(params.row.status).taskBtnType
            let btnStyle = null;
            if (params.row.taskMode == "normal") {
              btnStyle = "none"
            } else {
              btnStyle = "inline-block"
            }
            return h("div", [
              h('Poptip', {
                props: {
                  confirm: true,
                  'ok-text': '确定',
                  'cancel-text': '取消',
                  type: 'error',
                  size: 'large',
                  title: '你确定要删除吗?',
                  transfer: true
                },
                on: {
                  'on-ok': () => {
                    this.deleteTask(params.row.id)
                  },
                  'on-cancel': () => { }
                }
              }, [h('Button', {
                props: {
                  type: 'error',
                  size: 'small',
                  disabled:params.row.status == 'running' || params.row.status == 'starting'
                },
                style: {
                  margin: '5px'
                },
              }, '删除任务')]),
              h('Button', {
                props: {
                  type: "primary",
                  size: 'small',
                  disabled:params.row.status == 'running' || params.row.status == 'starting'
                },
                style: {
                  margin: '5px'
                },
                on: {
                  click: () => {
                    // _this.appProtocols()
                    _this.updateTask(params.row.id)
                  }
                }
              }, '修改任务'),
              h('Poptip', {
                props: {
                  confirm: true,
                  title: "确定要" + taskStatus + "吗？",
                },
                on: {
                  'on-ok': () => {
                    this.activeTask(params.row.id, taskStatus)
                  },
                  'on-cancel': () => {

                  }
                }
              }, [h('Button', {
                props: {
                  type: taskBtnType,
                  size: 'small'
                },
                style: {
                  margin: '5px',
                  display: btnStyle
                },
              }, taskStatus + '任务')]),
              // 不需要初始化
              // h('Poptip', {
              //   props: {
              //     confirm: true,
              //     title: "确定要初始化吗？",
              //   },
              //   on: {
              //     'on-ok': () => {
              //       this.initTask(params.row, "init")
              //     },
              //     'on-cancel': () => { }
              //   }
              // }, [h('Button', {
              //   props: {
              //     type: "info",
              //     size: 'small'
              //   },
              //   style: {
              //     margin: '5px'
              //   },
              // }, '初始化任务')]),
              h('Button', {
                props: {
                  type: "primary",
                  size: 'small'
                },
                style: {
                  margin: '5px'
                },
                on: {
                  click: () => {
                    this.taskDeail(params.row.id)
                  }
                }
              }, '查看详情'),
            ])
          }
        }
      ],
      targetTeamData: [],
      targetTeamTotal: 0,
      projectInfo: {},
      subnetList: [],
      networkId: '',
      idwithName: {},
      targetAllotList: [],
      targetAllotTotal: 0,
      targetTeamDataCopy: [],
      industryList: [],
      companyList: [], //所有单位列表


      // 

      configurationData: [],
      selectedDataConfiger: [],
      selectedVmDataTable: [],
      dataVmList: [],
      vmCurrentPage: 1,
      vmItemPage: 10,
      vmTotal: 0,
      columnsVmList: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '设备名称',
          key: 'deviceName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
        },
        {
          title: '端口名称',
          key: 'name',
          align: 'center',
          ellipsis: true,
          tooltip: true,
        },
        {
          title: 'IP',
          key: 'IP',
          align: 'center',
          render: (h, params) => {
            let value = params.row.IP;
            let oIP_ = [];
            value.forEach((item, i) => {
              oIP_.push(h("p", {
                color: '#000',
              }, item))
            })
            return h("div", oIP_)
          }
        },
        {
          title: '添加',
          key: 'add',
          align: 'center',
          width: 80,
          render: (h, params) => {
            return h('Button', {
              props: {
                type: 'primary',
              },
              on: {
                click: (e) => {
                  if (this.selectedVmDataTable.indexOf(params.row.id) != -1) {
                    this.$Message.info("已添加")
                    return;
                  }
                  this.addVmAfterTable(params.row)
                  this.selectedVmDataTable.push(params.row.id)
                  let oIP_ = '';
                  params.row.IP.forEach((item, i) => {
                    if (oIP_ == '') {
                      oIP_ = item;
                    } else {
                      oIP_ += "," + item
                    }
                  })
                  this.formValidate.selectedVmData.push({
                    "name": params.row.name,
                    "id": params.row.id,
                    "ip": oIP_
                  })
                }
              }
            }, "+");
          }
        }
      ],

      //查看详情面板
      taskDeailModal: false,
      taskDeailData: [],
      taskDeailColumns: [
        {
          type: "expand",
          width: '30',
          render: (h, params) => {
            return h('div', {}, [
              h('Row', { props: { class: 'expand-row' } }, [
                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                  h('span', { props: { class: 'expand-key' } }, 'deviceName:  '),
                  h('span', { props: { class: 'expand-value' } }, params.row.belongDeviceName)
                ]),
                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                  h('span', { props: { class: 'expand-key' } }, 'IP:  '),
                  h('span', { props: { class: 'expand-value' } }, params.row.ip)
                ]),
              ]),
              h('Row', { props: { class: 'expand-row' } }, [
                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                  h('span', { props: { class: 'expand-key' } }, 'cidr:  '),
                  h('span', { props: { class: 'expand-value' } }, params.row.cidr)
                ]),
                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                  h('span', { props: { class: 'expand-key' } }, 'mac:  '),
                  h('span', { props: { class: 'expand-value' } }, params.row.mac)
                ]),
              ]),
              h('Row', { props: { class: 'expand-row' }, }, [
                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                  h('span', { props: { class: 'expand-key' } }, 'cloudId:  '),
                  h('span', { props: { class: 'expand-value' } }, params.row.osId)
                ]),
                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                  h('span', { props: { class: 'expand-key' } }, 'hostIP:  '),
                  h('span', { props: { class: 'expand-value' } }, params.row.hostIp)
                ]),
              ]),
            ])
          }
        },
        {
          title: '名称',
          key: 'deviceName',
          align: 'center'
        },
        {
          title: '状态',
          key: 'status',
          align: 'center',
          render: (h, params) => {
            let obj = this.setStatusType(params.row.status)
            return h('Tag', {
              props: {
                color: obj.color,
              },
            }, obj.str)
          }
        },
        {
          title: '创建时间',
          key: 'created',
          align: 'center'
        },
        {
          title: '更新数据',
          key: 'updated',
          align: 'center'
        },
        {
          title: '信息',
          key: 'message',
          align: 'center'
        }
      ],
      properties: {},
      propertiesData: [],
      appProtocolsList: [],
    };
  },
  computed: {
    showQuestionList () {
      //选出部署了题目镜像虚拟机的题目
      let quesList = [];
      this.questionList.forEach((ques) => {
        if (this.allVms.map((vm) => vm.imageName).includes(ques.imageName)) {
          quesList.push(ques);
        }
      });
      return quesList;
    }
  },
  async mounted () {
    this.queryTaskList()
  },
  methods: {
    getMsgFormSon (data) {
      this.propertiesData = data;
    },
    // 删除任务采集任务
    deleteTask (id) {
      delTask(id).then(res => {
        if (res.code == 1) {
          this.$Message.success('删除成功')
          this.queryTaskList()
        } else {
          this.$Message.warning('删除失败')
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 开始，结束 
    activeTask (id, active) {
      let text = JSON.parse(JSON.stringify(active))
      if (active == "开始") {
        active = "start"
      } else if (active == "停止") {
        active = "stop"
      }
      operateExecute(id, active).then(res => {
        if (res.code == 1) {
          this.queryTaskList()
          this.$Message.success(text + "任务成功")
        } else {
          this.$Message.error(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 初始化
    initTask (row, init) {
      const { id: taskId, status } = row;
      if (status == "initialized" || status == 'completed' || status == 'failed') {
        operateExecute(taskId, init).then(res => {
          if (res.code == 1) {
            this.$Message.success('初始化任务成功')
            this.queryTaskList()
          } else {
            this.$Message.error(res.message)
          }
        }).catch(error => {
          this.$Message.error(error)
        })
      } else {
        this.$Message.info('非完成,失败,初始化状态下不可操作')
        return;
      }
    },

    // 查看详情
    taskDeail (id) {
      getHistoriesInfo(id).then(res => {
        if (res.code == 1) {
          this.taskDeailData = []
          this.taskDeailModal = true
          res.data.forEach(item => {
            this.taskDeailData.push({
              deviceName: item.deviceName,
              status: item.status,
              message: item.message,
              deviceId: item.deviceId,
              mac: '',
              hostIp: '',
              cidr: '',
              osId: '',
              ip: '',
              belongDeviceName: '',
              created: item.created ? item.created : '',
              updated: item.updated ? item.updated : '',
              _expanded: false
            })
          })
        } else {
          this.taskDeailData = []
          this.taskDeailModal = true
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 详情信息折叠信息
    hostDeail (row) {
      if (!row._expanded) {
        deployedPortsInfo(row.deviceId).then(res => {
          if (res.code == 1) {
            this.taskDeailData.forEach(item => {
              if (row.deviceId == item.deviceId) {
                item._expanded = true
                let ipsGroup = [];
                let cidrGroup = [];
                if (res.data.ips && res.data.ips.length != 0) {
                  for (let index = 0; index < res.data.ips.length; index++) {
                    const element = res.data.ips[index];
                    ipsGroup.push(element.ipAddress)
                    cidrGroup.push(element.cidr)
                  }
                }
                item.cidr = cidrGroup;
                item.hostIp = res.data.hostIp;
                item.mac = res.data.macAddress;
                item.osId = res.data.cloudId;
                item.ip = ipsGroup;
                item.belongDeviceName = res.data.deviceName;
                return false;
              }
            })
          } else {
            this.$Message.error(res.message)
          }
        })
      } else {
        row._expanded = !row._expanded;
      }
    },

    getTargetSize (size) {
      console.log('getTargetSize ~ size:', size)
      this.queryTargetAllotInfo.pageSize = size
      this.queryTaskList(1)
    },

    // 获取列表信息
    queryTaskList (val) {
      if (val) {
        this.queryTargetAllotInfo.pageIndex = val
      }
      let params = {
        testId: this.queryTargetAllotInfo.sceneId,
        // testId: '70b41c73-c02c-413f-82a3-84c89b7fe2aa',
        pageIndex: this.queryTargetAllotInfo.pageIndex,
        pageSize: this.queryTargetAllotInfo.pageSize,
        name:this.queryTargetAllotInfo.name,
        taskType: 'mirror_flow',
      }
      if (!params.name) {
        delete params.name
      }
      queryTaskList(params).then(res => {
        if (res.code == 1) {
          // console.log('====', res.data);
          this.targetAllotList = res.data.items
          this.targetAllotTotal = res.data.total
         let status =  this.targetAllotList.filter(item=> item.status == 'starting' || item.status == 'running' || item.status == 'closing')
        //  console.log('queryTaskList ~ status:', status)
          if(status && status.length > 0){
            setTimeout(()=>{
              this.queryTaskList()
            },30 * 1000)
          }
        } else {
          this.targetAllotList = []
          this.targetAllotTotal = 0
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 任务状态
    setStatusType (val) {
      let obj = {
        str: '',
        color: ''
      }
      switch (val) {
        case "running":
          obj.str = '运行中'
          obj.color = 'success'
          break;
        case "failed":
          obj.str = '失败'
          obj.color = 'error'
          break;
        case "error":
          obj.str = '失败'
          obj.color = 'error'
          break;
        case "completed":
          obj.str = '完成'
          obj.color = 'primary'
          break;
        case "initialized":
          obj.str = '初始化'
          obj.color = 'warning'
          break;
        case "starting":
          obj.str = '启动中'
          obj.color = 'success'
          break;
        case "closing":
          obj.str = '关闭中'
          obj.color = 'success'
          break;
        default:
          break;
      }
      return obj;
    },

    // 操作状态
    getStatusColor (val) {
      let obj = {
        taskStatus: null,
        taskBtnType: null,
      }
      switch (val) {
        case "initialized":
          obj.taskStatus = "开始"
          obj.taskBtnType = "success"
          break;
        case "error":
          obj.taskStatus = "开始"
          obj.taskBtnType = "success"
          break;
        case "failed":
          obj.taskStatus = "开始"
          obj.taskBtnType = "success"
          break;
        case "running":
          obj.taskStatus = "停止"
          obj.taskBtnType = "error"
          break;
        case "completed":
          obj.taskStatus = "开始"
          obj.taskBtnType = "success"
          break;
        case "starting":
          obj.taskStatus = "停止"
          obj.taskBtnType = "error"
          break;
        case "closing":
          obj.taskStatus = "停止"
          obj.taskBtnType = "error"
          break;
        case "stop_error":
          obj.taskStatus = "停止"
          obj.taskBtnType = "error"
          break;
        default:
          break;
      }
      return obj;
    },

    // 获取采集任务端口列表数据
    deployedProjectsList () {
      let params = {
        pageIndex: this.vmCurrentPage,
        pageSize: this.vmItemPage,
        projectId: this.routeParams.prjid,
        ipAddress: this.formValidate.vmIP,
        deviceName: this.formValidate.vmName,
        deviceType: 'VM',
      }
      if (!params.deviceName) {
        delete params.deviceName
      }
      if (!params.ipAddress) {
        delete params.ipAddress
      }
      this.dataVmList = [] // 清空一下
      deployedProjectsList(params.projectId, params).then(res => {
        if (res.code == 1) {
          let vmData = res.data.items;
          this.vmTotal = res.data.total;
          let disabled_ = false;
          let checked_ = false;
          vmData.forEach(item => {
            if (this.selectedVmDataTable.length != 0) {
              if (this.selectedVmDataTable.indexOf(item.id) != -1) {
                disabled_ = true
                checked_ = true
              } else {
                disabled_ = false
                checked_ = false
              }
            } else {
              disabled_ = false
              checked_ = false
            }
            let IPS = [];
            if (item.portIps && item.portIps.length != 0) {
              for (let index = 0; index < item.portIps.length; index++) {
                const element = item.portIps[index];
                IPS.push(element.ipAddress);
              }
            }
            this.dataVmList.push({
              name: item.name,
              id: item.id,
              IP: IPS,
              _disabled: disabled_,
              _checked: checked_,
              deviceName: item.deviceName
            })
          })
        } else {
          this.dataVmList = []
          this.vmTotal = 0
          this.$Message.error(data.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    showAddAndUpdate () {
      this.targetModal.show = true;
      this.targetModal.type = 1;
      this.propertiesData = [{
        key: '',
        value: '',
      }];
      // this.selectedDataConfiger = [];
      // this.selectedVmDataTable = [];
      
      this.targetModal.title = '采集任务'
      // this.appProtocols()
      this.deployedProjectsList()
    },

    appProtocols () {
      appProtocols().then(res => {
        if (res.code == 1) {
          console.log('==', res.data);
          this.appProtocolsList = res.data
        } else {
          this.appProtocolsList = []
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 搜索
    refreshVmList () {
      this.vmCurrentPage = 1;
      this.deployedProjectsList()
    },

    getSelectedData (selection) {
      // console.log(selection)
      this.selectedDataConfiger = [];
      this.selectedDataConfiger = selection;
    },

    switchineVmCurrentPage (numberPage) {
      this.vmCurrentPage = numberPage;
      this.deployedProjectsList()
    },
    switchVmItemPage (numberSize) {
      this.vmItemPage = numberSize
      this.deployedProjectsList()
    },

    // 添加列表数据
    addSelectedData () {
      let that = this, bol = true;
      that.selectedDataConfiger.forEach(function (item, i) {
        if (that.selectedVmDataTable.indexOf(item.id) != -1) {

        } else {
          bol = false
          that.addVmAfterTable(item)
          that.selectedVmDataTable.push(item.id)
          that.formValidate.selectedVmData.push({
            "name": item.name,
            "id": item.id,
            'ip': item.IP[0]
          })
        }
      })
      if (bol) {
        that.$Message.info("请选择要添加的内容")
      }
    },

    // 取消
    closeTargetModal () {
      this.addTarget = false;
      //	    	this.handleReset('formValidate');
      //	    	this.handleReset('addFormValidate');
    },

    // 提交
    handleSubmit (name) {
      // 属性
      this.properties = {};
      if (this.propertiesData.length != 0) {
        let attrData = this.propertiesData;
        for (let index = 0; index < attrData.length; index++) {
          const element = attrData[index];
          if (element.key) {
            this.properties[element.key] = element.value;
          }
        }
      }
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.selectedVmDataTable.length != 0) {
            let params = {
              configId: this.formValidate.configContent, // 配置
              description: this.formValidate.desc, // 描述
              name: this.formValidate.name,
              deviceIdList: this.selectedVmDataTable,
              deviceType: "P",
              taskType: 'mirror_flow',
              testId: this.$route.query.id,
              properties: this.properties, // 属性
              taskMode: this.formValidate.taskMode,
              metadata: { proto: this.formValidate.metadata }, //协议
            }
            console.log('===this.targetModal.type', this.targetModal.type);
            if (this.targetModal.type == 1) {//判断是新增还是修改 1 为新增 2修改
              this.saveoutbandTask(name,params)
            } else {
              this.amendTask(name,params)
            }
          } else {
            this.$Message.info("请选择端口")
            this.targetModal.loading = false;
            this.$nextTick(() => {
              this.targetModal.loading = true;
            });
          }
        } else {
          this.targetModal.loading = false;
          this.$nextTick(() => {
            this.targetModal.loading = true;
          });
        }

      });
    },

    saveoutbandTask (name,saveDateJson) {
      addTask(saveDateJson).then((res) => {
        if (res.code == 1) {
          this.targetModal.show = false;
          this.queryTargetAllotInfo.pageIndex = 1
          this.queryTargetAllotInfo.pageSize = 10
          this.$Message.success('添加任务成功');
          this.$refs[name].resetFields();
          this.queryTaskList()
          this.targetModal.loading = false;
          this.$nextTick(() => {
            this[name].selectedVmData = []
            this.targetModal.loading = true;
          });
        } else {
          this.$Message.error(res.message)
          this.targetModal.loading = false;
          this.$nextTick(() => {
            this.targetModal.loading = true;
          });
        }
      })
    },

    amendTask (name,amendTaskData) {
      updateTask(this.workingAreaTaskId, amendTaskData).then((res) => {
        if (res.code == 1) {
          this.queryTargetAllotInfo.pageIndex = 1
          this.queryTargetAllotInfo.pageSize = 10
          this.$Message.success('修改成功');
          this.$refs[name].resetFields();
          this[name].selectedVmData = []
          this.queryTaskList()
          this.targetModal.show = false;
          this.targetModal.loading = false;
        } else {
          this.$Message.error(res.message)
          this.targetModal.loading = false;
          this.$nextTick(() => {
            this.targetModal.loading = true;
          });
        }
      })
    },

    // 修改任务
    updateTask (taskId) {
      this.formValidate.vmName = "";
      this.formValidate.vmIP = "";
      this.targetModal.title = '修改采集任务'
      this.targetModal.type = 2;
      getTaskDetail(taskId).then((res) => {
        if (res.code == 1) {
          this.workingAreaTaskId = res.data.id
          this.selectedVmDataTable = []
          this.formValidate.selectedVmData = []
          this.targetModal.show = true;
          this.propertiesData = [];
          this.formValidate.name = res.data.name;
          this.formValidate.desc = res.data.description;

          this.formValidate.configContent = res.data.configId;
          this.formValidate.metadata = res.data.metadata == null ? { proto: '' } : res.data.metadata.proto
          if (res.data.deviceData.length != 0) {
            console.log(res.data.deviceData);
            res.data.deviceData.forEach(item => {
              this.selectedVmDataTable.push(item.deviceId);
              this.formValidate.selectedVmData.push({
                name: item.deviceName,
                id: item.deviceId,
                ip:item.ip
              })
            })
          }
          this.formValidate.taskMode = res.data.taskMode;
          if (JSON.stringify(res.data.properties) != "{}") {
            for (let i in res.data.properties) {
              let obj = {};
              obj['key'] = i;
              obj['value'] = res.data.properties[i];
              this.propertiesData.push(obj)
            }
          }
        } else {
          this.workingAreaTaskId = ""//清空任务id
          this.$Message.error(res.message)
        }
      }).then(() => {
        this.deployedProjectsList()
        this.judgeVmStatus()
      })
    },

    judgeVmStatus () {
      let data = this.dataVmList;
      let data_ = this.selectedVmDataTable
      // console.log(data_)
      data.forEach(function (item, i) {
        // console.log(item.id)
        if (data_.indexOf(item.id) != -1) {
          // alert('-')
          item._checked = true;
          item._disabled = true;
        } else {
          item._checked = false;
          item._disabled = false;
        }
      })
    },

    handleClose2 (event, name) {
      // console.log(event)
      // console.log(name);
      let $this = this;
      let data = this.formValidate.selectedVmData;
      $this.selectedDataConfiger = [];
      let _data = this.selectedVmDataTable;
      data.forEach(function (item, i) {
        if (item) {
          if (item.name == name) {
            data.splice(i, 1);
            // _data.remove(name);
            _data.splice($this.selectedVmDataTable.findIndex(vmId => vmId == name), 1);
            $this.judgeVmStatus()
          }
        }
      });

    },

    addVmAfterTable (param) {
      let data = this.dataVmList;
      this.dataVmList.forEach(function (item, i) {
        if (item.id == param.id) {
          item._checked = true;
          item._disabled = true;
        }
      })
    },

    // 模态框关闭后清空搜索条件
    modalVisibleChange (type) {
      // console.log('type:', type)
      if (!type) {
        this.formValidate.selectedVmData = [];
        this.$refs.formValidate.resetFields();
        this.selectedDataConfiger = [];
        this.selectedVmDataTable = [];
      }
    },


    // 防抖封装
    getData: debounce(() => { }),

  }
}
</script>

<style scoped>
.account-target-modal >>> .starlet {
  color: #ed4014;
  position: absolute;
  left: -46px;
  font-size: 12px;
  font-family: SimSun;
  line-height: 33px;
  /* font-weight: 800; */
}
.account-target-modal >>> .pageStyleVm {
  text-align: center;
  margin-top: 10px;
}
.targetHeader {
  /*padding: 10px;*/
  margin: 15px 0px;
}
.account-target-modal /deep/ .ivu-modal {
  height: calc(100vh - 200px);
  min-height: 520px;
}
.account-target-modal /deep/ .ivu-modal .ivu-modal-content {
  height: 100%;
}
.account-target-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body {
  height: calc(100% - 112px);
}
.search-group {
  width: calc(100% + 32px);
  margin-left: -16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8eaec;
}
.account-target-modal
  /deep/
  .ivu-modal
  .ivu-modal-content
  .ivu-modal-body
  > form {
  height: calc(100% - 65px);
  overflow: auto;
}

.headerBtn {
  text-align: left;
  margin: 10px;
}
.pageStyle {
  text-align: right;
}
.ivu-table-wrapper {
  overflow: visible;
}
.pageStyleVm {
  text-align: center;
}
/* table .ivu-poptip-confirm .ivu-poptip-body .ivu-icon {
  left: 11px;
} */
/* .position_i {
  position: relative;
  top: -1px;
  margin-right: 5px;
} */
/* td{
    border-right: 0 !important
} */
/* .ivu-table-tip {
  overflow: hidden !important;
} */
/* .starlet {
  color: red;
  position: absolute;
  left: -60px;
  font-size: 18px;
  line-height: 38px;
  font-weight: 800;
} */
.zIndexStyleBtn {
  position: relative;
  z-index: 55;
}
/* /deep/ .ivu-poptip-confirm .ivu-poptip-body .ivu-icon {
  left: 12px;
  top: 22px;
} */
</style>


